//
//  CWQ_historySearchVC.m
//  BaxTer
//
//  Created by 陈武琦 on 16/9/13.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "CWQ_historySearchVC.h"
#import "CWQ_historySearchCell.h"
#import "CWQ_searchView.h"
#import "YYHeaderView.h"
#import "CWQ_SearchVC.h"
#import "Masonry.h"
static NSString * const cellId = @"CWQ_historySearchCellID";
@interface CWQ_historySearchVC ()<UITextFieldDelegate, UIAlertViewDelegate>{

CWQ_searchView * searchView;
}

@end

@implementation CWQ_historySearchVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        //默认是课程搜索
        self.searchType = CWQ_historySearchVCType_Course_ShangXueyuan;
        self.flagId  = -1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CWQ_historySearchCell" bundle:nil] forCellReuseIdentifier:cellId];
    weakSelf_define;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).with.offset(0);
        make.right.equalTo(weakSelf.view).with.offset(0);
        make.top.equalTo(weakSelf.view).with.offset(0);
        make.bottom.equalTo(weakSelf.view).with.offset(0);
    }];
    [self setupSearchView];
    [self setupData];
    // Do any additional setup after loading the view.
}


-(void)setupSearchView
{
    searchView = [CWQ_searchView creatView];
    searchView.frame = CGRectMake(0, 0, kScreenWidth, 40);
   
    weakSelf_define;
    [searchView setCWQGetTitle:^(NSString * title)
     {
        
         [weakSelf searchKeyWords:title];
     }];

    self.navigationItem.titleView = searchView;
}

-(void)setupData
{
   NSString *sql = @"SELECT * FROM BTHistorySearchM WHERE rowid>=0 ORDER BY rowid DESC";//第一页
    self.dataArray = [BTHistorySearchM searchWithSQL:sql];
    [self.tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated{
    [self setupData];
}

-(void)searchKeyWords:(NSString *)keyWords
{
    if ([keyWords isEqualToString:@""] || keyWords == nil)
    {
        return;
    }
    [searchView endEditing:YES];
    [self loadSearchDataWithKeyWord:keyWords];
    [self pushToSearchVCWithKey:keyWords];
}

- (void)loadSearchDataWithKeyWord:(NSString *)keyword
{
    for (int i = 0; i< self.dataArray.count; i++)
    {
        BTHistorySearchM *model = self.dataArray[i];
        if ([model.title isEqual:keyword] == YES)
        {
            [model deleteToDB];
            [self.dataArray removeObject:model];
        }
    }
    NSDictionary * dict2 = @{@"title":keyword};
    BTHistorySearchM *model = [BTHistorySearchM mj_objectWithKeyValues:dict2];
    [self.dataArray insertObject:model atIndex:0];
    //写入本地
    NSString *tag =nil ;

    switch (self.searchType) {
        case CWQ_historySearchVCType_Course_ShangXueyuan:
            tag = @"商学院";
            break;
        case CWQ_historySearchVCType_Course_Market:
            
            tag = @"市场";
            break;
        case CWQ_historySearchVCType_Course_Sale_all:
        case CWQ_historySearchVCType_Course_FlagSale:
            tag = @"销售";
            break;
        case CWQ_historySearchVCType_Topic:
            tag = @"专题";
            break;
        case CWQ_historySearchVCType_Course_Guanli:
        case CWQ_historySearchVCType_Course_FlagGuanli:
            tag = @"管理学院";
            break;
    
        case CWQ_historySearchVCType_Consult:
            tag = @"资讯";
            break;
            
        default:
            break;
    }
    model.tag = tag;
    [model saveToDB];
    [self.tableView reloadData];
}

- (void)pushToSearchVCWithKey:(NSString *)key {
    CWQ_SearchVC *searchVC = [[CWQ_SearchVC alloc] initWithSearchWords:key withType:self.searchType];
    searchVC.flagId = self.flagId;
    searchVC.hidesBottomBarWhenPushed = YES;
    NSMutableArray *ViewCtr = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    WSJLog(@"navigation viewControllers is %@", ViewCtr);
    int index = (int)[ViewCtr indexOfObject:self];
    [ViewCtr removeObjectAtIndex:index];
    [ViewCtr addObject:searchVC];
    WSJLog(@"the viewCtl is %@", ViewCtr);
    [self.navigationController setViewControllers:ViewCtr animated:YES];

}

- (void)clearHistoryRecords
{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否要清空历史记录" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        for (BTHistorySearchM *model in self.dataArray) {
            [model deleteToDB];
        }
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
    }
}
#pragma mark ----------------tableview代理--------------------------

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return @"";
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    if (self.dataArray.count <= 0) {
//        return 0;
//    }
    return 1;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    YYHeaderView * header = [YYHeaderView creatView];
    [header titleHeader:@"历史搜索"];
    weakSelf_define;
    [header setYYCleanBut:^{
        [weakSelf clearHistoryRecords];
    }];
    return header;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section

{
    return 44;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.dataArray count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CWQ_historySearchCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    //设置cell 的分割线
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    [cell setModel:self.dataArray[indexPath.row]];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 33;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [searchView endEditing:YES];
    BTHistorySearchM *model = self.dataArray[indexPath.row];
    [self pushToSearchVCWithKey:model.title];
}





@end
